import { msalInstance, loginRequest } from "./authConfig";

export function getAccount() {
  const accounts = msalInstance.getAllAccounts();
  console.log("获取账户信息:", accounts);
  return accounts.length > 0 ? accounts[0] : null;
}

export async function handleRedirectCallback() {
  try {
    loginRequest.redirectUri = "/";
    const response = await msalInstance.loginRedirect(loginRequest);
    return response;
  } catch (error) {
    console.error("Redirect登录失败:", error);
    throw error;
  }
}

export async function getAccessToken() {
  const account = getAccount();
  if (!account) throw new Error("未登录账户");

  const tokenRequest = {
    scopes: loginRequest.scopes,
    account,
  };

  try {
    const response = await msalInstance.acquireTokenSilent(tokenRequest);
    return response.accessToken;
  } catch {
    const response = await msalInstance.acquireTokenRedirect(tokenRequest);
    return response.accessToken;
  }
}
